<template>
  <div class="page editQrCode">
    <awesome-picker
      v-if="picker1Visible"
      ref="picker1"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :textTitle="picker1.textTitle"
      :data="picker1.data"
      :anchor="picker1.anchor"
      @confirm="handlePicker1Confirm"
      @cancel="handlePicker1Cancel"
      class="pickerZindex"
    ></awesome-picker>
    <awesome-picker
      ref="picker2"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :textTitle="picker2.textTitle"
      :data="picker2.data"
      :anchor="picker2.anchor"
      @confirm="handlePicker2Confirm"
      @cancel="handlePicker2Cancel"
      class="pickerZindex"
    ></awesome-picker>
    <payMoney ref="payMoney" :listData="list" :shopName="shopName"></payMoney>
    <div class="scroll-view">
      <customHeader :middleTitle="middleTitle" @leftCallBack="handleBack"></customHeader>
      <div class="page-body">
        <!-- <div class="code-type">当前创建类型: {{codeType}}</div> -->
        <ul class="ope-list">
          <li class="readOnly" v-if="type===1">
            <span>码ID</span>
            <div>{{details.qrcodeId}}</div>
          </li>
          <li v-if="type===0&&openStatus" :class="{'readOnly':!openStatus}">
            <span>码类型</span>
            <div class="pick-value" @click="showPicker('picker2',!openStatus)">
              {{picker2.selected.text}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li class="readOnly" v-if="type===1||!openStatus">
            <span>码类型</span>
            <div>{{codeType}}</div>
          </li>
          <li>
            <span>收款码名称</span>
            <div>
              <inputClear
                warpClass="codeName"
                placeholder="请输入收款码名称"
                v-model="details.qrcodeName"
                :maxlength="15"
                :max="15"
              />
            </div>
          </li>
          <li :class="{readOnly:type==1&&details.cashierId}">
            <span>收银员</span>
            <div class="pick-value" @click="showPicker('picker1',type==1&&details.cashierId)">
              {{picker1.selected.text}}
              <i class="zhk-list_rarrow"></i>
            </div>
          </li>
          <li>
            <span>设置金额</span>
            <div>
              <mt-switch v-model="isOpenAmount"></mt-switch>
            </div>
          </li>
        </ul>
        <div class="explainText">开启固定金额功能，顾客扫码支付时将支付设置的固定金额。关闭固定金额功能，顾客扫码支付时需要手动输入金额。</div>
        <ul class="set-money-list" v-if="isOpenAmount">
          <template v-for="(item,index) in list">
          <li :key="index" v-if="item.isDelete!=1">
            <div class="inputContent">
              <div class="inputItem">
                <span>固定金额</span>
                <inputClear placeholder="请填写金额" v-model="item.payAmount" :limitVal="limitVal"/>元
              </div>
              <div class="inputItem">
                <span>收款内容</span>
                <inputClear placeholder="请填写收款项名称，如单人套餐" v-model="item.payContent" :maxlength="10"/>
              </div>
            </div>
            <i class="zhk-list_sc" v-if="editNum>1" @click="deleteItem(index, item)"></i>
          </li>
          </template>
        </ul>
        <!-- <div :class="list.length>=6?'addButtonDisabled':'addButton'" v-if="isOpenAmount" @click="addButton">
          <div class="btn">+ 增加</div>
        </div> -->
        <div :class="editNum>=6?'addButtonDisabled':'addButton'" v-if="isOpenAmount" @click="addButton">
          <div class="btn">+ 增加</div>
        </div>
        <div class="viewPreviewImg" v-if="isOpenAmount">
          <span @click="viewPreviewImg">查看扫码预览图</span>
        </div>
        <div class="btn-wrap">
          <div class="btn" @click="submitJudge">提交</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import inputClear from "../../components/inputClear/inputClear";
import { Toast, MessageBox, Switch } from "mint-ui";
import jsBridge from "../../tools/jsBridge";
import payMoney from "./payMoney";
import AwesomePicker from "vue-awesome-picker";
Vue.use(AwesomePicker);
Vue.component(Switch.name, Switch);

export default {
  name: "editQrCode",
  data() {
    return {
      CommonUtil: CommonUtil,
      loadding: false,//提交中
      openStatus: false,//门店是否开通小程序
      shopId: "",
      shopName: '',
      details: {
        id: "",
        cashierId: "",
        shopId: "",
        qrcodeId: "",
        qrcodeName: "",
        qrcodeType: "",
      },
      middleTitle: "新增收款码",
      picker1Visible: false,
      picker1: {
        anchor: [],
        textTitle: "收银员",
        selected: { text: "不限" },
        data: [{ value: "不限", id: "" }]
      },
      picker2: {
        anchor: [],
        textTitle: "码类型",
        selected: { text: "请选择" },
        data: [{ value: "请选择", id: "" }, { value: "基础码", id: 1 }, { value: "小程序码", id: 2 }]
      },
      isOpenAmount: false,
      list: [{
        payAmount: "",
        payContent: ""
      }],
      isInintStaus: true,
      editNum: 1,
      contentChanged: false//内容有无变动
    };
  },
  watch: {
    "details.qrcodeName"(newVal, oldVal) {
      if (!this.isInintStaus && this.$route.query.type == 1) {
        if (newVal != oldVal) {
          this.contentChanged = true;
        }
      }
    },
    isOpenAmount(newVal, oldVal) {
      if (!this.isInintStaus && this.$route.query.type == 1) {
        if (newVal != oldVal) {
          this.contentChanged = true;
        }
      }
    },
    list: {
      handler(newVal, oldVal) {
        if (!this.isInintStaus && this.$route.query.type == 1) {
          this.contentChanged = true;
          // if (newVal != oldVal) {
          //   this.contentChanged = true;
          // }
        }
        let num = 0;
        this.list.forEach(item=> {
          if(item.isDelete!=1) num++;
        });
        this.editNum = num;
      },
      deep: true,
      // immediate: true
    },
  },
  methods: {
    handleBack() {
      MessageBox.close(false);
      this.$router.back();
    },
    //重置下拉为不限
    pickerReset() {
      this.picker1 = {
        anchor: [],
        textTitle: "收银员",
        selected: { text: "不限", value: "" },
        data: [{ value: "不限", id: "" }]
      };
    },
    limitVal(val) {
      val = val.replace(/[^\d.]/g, "").replace(/^\./g, "").replace(/\.{2,}/g, ".");
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); 
      val = Number(val) > 99999.99 ? 99999.99 : val;
      return val;
    },
    submitJudge() {
      if (!this.details.qrcodeName) {
        Toast("请输入收款码名称");
        return;
      }
      if (this.details.qrcodeType == null || this.details.qrcodeType == "") {
        Toast("请选择码类型");
        return;
      }
      if(this.isOpenAmount) {
        let flag = true;
        this.list.forEach(item=> {
          flag = flag && item.payAmount && item.payContent
        });
        if(!flag) {
          Toast("固定金额、收款内容不能为空");
          return;
        }
      }
      if (this.$route.query.type == 1) {
        // 编辑收款码页面内容是否有变动
        if (this.contentChanged) {
          const html = `
            <div class='mesBox'>
              <p>本次修改会使顾客支付内容发生变化，请确认是否修改？</p>
              <p>Tips：码名称修改会更新当前收款二维码，如线下已经铺设，请及时替换</p>
            </div>
          `;
          MessageBox({
            title: "提示",
            message: html,
            confirmButtonText: "提交修改",
            cancelButtonText: "放弃提交",
            showCancelButton: true
          }).then(action => {
            if (action == "confirm") {
              this.submit();
            }
          });
        } else {
          this.submit();
        }
      } else {
        this.submit();
      }
    },
    submit() {
      if (this.loadding) {
        return;
      }
      let params = { 
        shopId: this.shopId, 
        qrcodeType: this.details.qrcodeType, 
        cashierId: this.picker1.selected.value, 
        qrcodeName: this.details.qrcodeName, 
        qrcodeId: this.details.qrcodeId,
        isOpenAmount: +this.isOpenAmount
      };
      if(this.isOpenAmount) {
        params.qrcodeAmountParamsList = this.list;
      }
      let reqUrl = "/newapp/code/addQEcode.do";
      if (this.details["id"]) {
        params.id = this.details["id"];
        reqUrl = "/newapp/code/modifyQEcode.do";
      }
      this.loadding = true;
      this.ajax({
        url: reqUrl,
        type: "post",
        data: params,
        controlLoading: true
      }).then(response => {
        if (response && response.success) {
          Toast({ message: '提交成功', duration: 2000 });
          this.$router.back();
        } else {
          this.loadding = false;
          Toast(response.msg);
        }
      }).catch((err) => {
        this.loadding = false;
      });
    },
    //收银员选择回调
    handlePicker1Confirm(v) {
      this.picker1.anchor = v;
      this.picker1.selected.value = this.picker1.data[v[0].index].id;
      this.picker1.selected.text = v[0].value;
      this.picker1Visible = false;
    },
    handlePicker1Cancel() {
      this.picker1Visible = false;
    },
    //码类型选择回调
    handlePicker2Confirm(v) {
      this.picker2.anchor = v;
      this.picker2.selected.value = this.picker2.data[v[0].index].id;
      this.details.qrcodeType = this.picker2.selected.value;
      this.picker2.selected.text = v[0].value;
    },
    handlePicker2Cancel() {
      this.picker2Visible = false;
    },
    //点击请选择弹出选择项
    showPicker(ref, disabled = false) {
      if (disabled) {
        return;
      }
      this[ref + "Visible"] = true;
      this.$nextTick(() => {
        this.$refs[ref].show();
      });
    },
    //获取收银员数据
    getCashierList(callBack) {
      this.ajax({
        url: `/mini/qecodeManage/getCashierList.do?shopId=${this.shopId}`,
        type: "get",
        controlLoading: false
      }).then(response => {
        this.pickerReset();
        if (response && response.success) {
          const data = response.resultObject;
          if (data && data.length > 0) {
            this.picker1.data = this.picker1.data.concat(
              CommonUtil.formatPickerData(data, "name", "accountId")
            );
            callBack && callBack();
          }
        } else {
          Toast(response.msg);
        }
      }).catch(err=> {

      });
    },
    //查询门店开通小程序状态
    getOpenMiniStatus() {
      //serviceCode 服务状态： 1_0：未开通； 1_1：待开通微信收款； 1_2：收款码待激活； 1_3：已开通
      this.ajax({
        url: `/applet/manager/queryHasOpenedYzProShop.do?shopId=${this.shopId}&serviceCode=9&serviceStatus=1_3`,
        type: "get",
        controlLoading: false
      }).then(response => {
        if (response && response.success) {
          const data = response.resultObject;
          if (data && data.length > 0) {
            this.openStatus = true;
            //this.details.qrcodeType = 2;
          } else {
            this.openStatus = false;
            this.details.qrcodeType = 1;
          }
        } else {
          Toast(response.msg);
        }
      }).catch(err=> {

      });
    },
    //绑定收银员到下拉框
    bindCashier() {
      if (this.$route.query['info'] && this.$route.query.info['cashierId']) {
        const cashierId = this.$route.query.info['cashierId']
        const selectedItem = this.picker1.data.filter((item) => {
          return item.id == cashierId;
        });
        this.picker1.selected.text = selectedItem[0].value;
        this.picker1.selected.value = selectedItem[0].id;
      }
    },
    deleteItem(vIndex, item) {
      if(item && item.id) {
        item.isDelete = 1;
        return;
      }
      this.list.splice(vIndex, 1);
    },
    addButton() {
      if(this.editNum<6) {
        const listItem = {
          payAmount: "",
          payContent: ""
        };
        this.list.push(listItem);
      }
    },
    viewPreviewImg() {
      this.$refs.payMoney.popupShow();
    },
    getQrcodeInfo(id) {
      this.ajax({
        url: '/newapp/code/queryqrcode.do',
        type: "get",
        data: {
          qrcodeId: id
        },
        controlLoading: true
      }).then(res => {
        if(res.success) {
          let resObj = res.resultObject;
          this.isOpenAmount = resObj.isOpenAmount == 1;
          if(this.isOpenAmount && resObj.qrcodeAmountParamsList) {
            this.list = resObj.qrcodeAmountParamsList;
          }
          this.$nextTick(()=> {
            this.isInintStaus = false;
          });
        }else {
          Toast(res.msg);
        }
      }).catch((err) => {

      });
    }
  },
  computed: {
    codeType() {
      let ct = "基础码";
      if (this.$route.query.type == 1) {
        if (this.details.qrcodeType == 2) {
          ct = "小程序码";
        }
      } else {
        if (this.openStatus) {
          ct = "小程序码";
        }
      }
      return ct;
    }
  },
  created() {
    const type = this.$route.query.type;
    this.shopId = this.$route.query.shopId;
    this.shopName = this.$route.query.shopName;
    this.getCashierList(this.bindCashier);
    if (this.$route.query['info']) {
      this.details = this.$route.query.info;
      this.getQrcodeInfo(this.details.qrcodeId);
    } else {
      this.getOpenMiniStatus();
    }
    this.type = type;
    this.middleTitle = type === 1 && !this.$route.query['title'] ? "编辑收款码" : "新增收款码"; //0:新增，1：编辑
  },
  components: {
    customHeader,
    inputClear,
    payMoney
  }
};
</script>

<style lang='scss' scoped>
@import "getMoneyQrCode";
</style>
<style lang='scss'>
.inputItem, .ope-list {
  .input-clear-wrap input {
    text-align: right!important;
  }
}
</style>

